package com.flyco.modules.log.service.impl;

import com.flyco.common.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flyco.common.util.MD5Util;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.pms.entity.PmsProductPriceRegulate;
import com.flyco.modules.pms.model.PmsProductSkuModel;
import com.flyco.modules.pms.service.IPmsProductPriceRegulateService;
import com.flyco.modules.log.entity.LogSyncSkuPrice;
import com.flyco.modules.log.mapper.LogSyncSkuPriceMapper;
import com.flyco.modules.log.service.ILogSyncSkuPriceService;
import com.flyco.modules.system.entity.SysPartner;
import com.flyco.modules.util.ApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.flyco.common.util.DateUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description: 商品价格同步日志
 * @Author: flyco
 * @Date:   2020-03-03
 * @Version: V1.0
 */
@Slf4j
@Service
public class LogSyncSkuPriceServiceImpl extends ServiceImpl<LogSyncSkuPriceMapper, LogSyncSkuPrice> implements ILogSyncSkuPriceService {

    @Autowired
    private IPmsProductPriceRegulateService productPriceRegulateService;

    static final String OMS_SECRET = "E62tGaYSCVMQ7s0Nhcr8sCc6tb27z4vb";

    @Override
    public void syncSkuPrice() {
        StringBuilder url = new StringBuilder();
        url.append(ApiUtil.getOmsUrl());
        url.append("price/list");
        log.info("url:" + url.toString());
        String result = HttpUtil.getRequest(url.toString());
        /*String result = HttpUtil.createGet(url.toString())
                .contentType("application/json")
                .execute()
                .body();*/
        log.info("result:" + result);

        LogSyncSkuPrice syncLog = new LogSyncSkuPrice();
        syncLog.setOmsJson(result);
        List<PmsProductPriceRegulate> skuPrices = createProductPriceRegulate(result);
        syncLog.setMallJson(JSON.toJSONString(skuPrices));
        syncLog.setCreateTime(new Date());
        this.save(syncLog);

        productPriceRegulateService.updateByListWithOutId(skuPrices, 0L);

        log.info("result:" + skuPrices);
    }

    private List<PmsProductPriceRegulate> createProductPriceRegulate(String json) {
        if (oConvertUtils.isEmpty(json)) return null;
        JSONObject jobj = JSON.parseObject(json);
        if (oConvertUtils.isEmpty(jobj) || oConvertUtils.isEmpty(jobj.getJSONArray("data"))) return null;
        Map<String, PmsProductPriceRegulate> regulateMap = new HashMap<String, PmsProductPriceRegulate>();
        JSONArray jsonArray = jobj.getJSONArray("data");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            PmsProductPriceRegulate productPriceRegulate = regulateMap.get(jsonObject.getString("productCode"));
            if (oConvertUtils.isEmpty(productPriceRegulate)){
                productPriceRegulate = new PmsProductPriceRegulate();
            }
            if("activity".equalsIgnoreCase(jsonObject.getString("mark"))) {
                productPriceRegulate.setMinPrice(new BigDecimal(jsonObject.getString("price")));
            } else if("standard".equalsIgnoreCase(jsonObject.getString("mark"))) {
                productPriceRegulate.setNormalPrice(new BigDecimal(jsonObject.getString("price")));
            }
            regulateMap.put(jsonObject.getString("productCode"),productPriceRegulate);
        }

        List<PmsProductSkuModel> productSkuModels = productPriceRegulateService.getProductSkuModel(0L);

        List<PmsProductPriceRegulate> regulates = new ArrayList<>();

        for (PmsProductSkuModel model : productSkuModels) {
            PmsProductPriceRegulate regulate = regulateMap.get(model.getSkuCode());
            if (oConvertUtils.isNotEmpty(regulate)){
                regulate.setProductSn(model.getProductSn());
                regulate.setSyncTime(new Date());
                regulates.add(regulate);
            }
        }
        return regulates;
    }

    @Override
    public void syncSkuPrice2(SysPartner partner) {
        // http://192.168.20.151:11033/api/product/getProductSkuPrice?shopId=185&dateTime=2022-05-16 00:00:00&sign=6d36cf436724fd407479fe0d1700be09&timestamp=1652347815

        String shopId = partner.getExtCode();
        String dateTime = DateUtils.date2Str(DateUtils.beginOfDay(new Date()),DateUtils.datetimeFormat.get());
        int timestamp = (int)(DateUtils.getMillis()/1000);
        String sign = MD5Util.MD5Encode(shopId + dateTime + timestamp + OMS_SECRET, "utf-8");


        StringBuilder url = new StringBuilder();
        url.append(ApiUtil.getOmsUrl());
        url.append("api/product/getProductSkuPrice");
        url.append("?shopId=");
        url.append(shopId);
        url.append("&dateTime=");
        try {
            url.append(URLEncoder.encode(dateTime, "UTF-8"));
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }

        url.append("&sign=");
        url.append(sign);
        url.append("&timestamp=");
        url.append(timestamp);
        log.info("url:" + url.toString());
        String result = HttpUtil.postRequest(url.toString());
        log.info("result:" + result);

        LogSyncSkuPrice syncLog = new LogSyncSkuPrice();
        syncLog.setOmsJson(result);
        List<PmsProductPriceRegulate> skuPrices = createProductPriceRegulate2(result, partner.getId());
        syncLog.setMallJson(JSON.toJSONString(skuPrices));
        syncLog.setCreateTime(new Date());
        this.save(syncLog);

        productPriceRegulateService.updateByListWithOutId(skuPrices, partner.getId());

        log.info("result:" + skuPrices);
    }

    private List<PmsProductPriceRegulate> createProductPriceRegulate2(String json , Long partnerId) {
        if (oConvertUtils.isEmpty(json)) return null;
        JSONObject jobj = JSON.parseObject(json);
        if (oConvertUtils.isEmpty(jobj) || oConvertUtils.isEmpty(jobj.getJSONArray("data"))) return null;
        Map<String, PmsProductPriceRegulate> regulateMap = new HashMap<String, PmsProductPriceRegulate>();
        JSONArray jsonArray = jobj.getJSONArray("data");
        for (int i = 0; i < jsonArray.size(); i++) {
            /**
             *         {
             *             "skuCode": "6949123309031",
             *             "sapItemCode": "1200100100252",
             *             "price": 169.0,
             *             "beginDate": "2022-04-18 00:00:00",
             *             "endDate": "2022-12-31 00:00:00",
             *             "typeId": 0   //价格类型： 0-正常价格，1促销价格
             *         }
             */


            JSONObject jsonObject = jsonArray.getJSONObject(i);
            PmsProductPriceRegulate productPriceRegulate = regulateMap.get(jsonObject.getString("skuCode"));
            if (oConvertUtils.isEmpty(productPriceRegulate)){
                productPriceRegulate = new PmsProductPriceRegulate();
                productPriceRegulate.setSkuCode(jsonObject.getString("skuCode"));
                productPriceRegulate.setSapItemCode(jsonObject.getString("sapItemCode"));
                productPriceRegulate.setSyncTime(new Date());
                productPriceRegulate.setPartnerId(partnerId);
            }
            if(Objects.equals(1,jsonObject.getInteger("typeId"))) {
                productPriceRegulate.setMinPrice(new BigDecimal(jsonObject.getString("price")));
            } else if(Objects.equals(0,jsonObject.getInteger("typeId"))) {
                productPriceRegulate.setNormalPrice(new BigDecimal(jsonObject.getString("price")));
            }
            regulateMap.put(jsonObject.getString("skuCode"),productPriceRegulate);
        }

        List<PmsProductSkuModel> productSkuModels = productPriceRegulateService.getProductSkuModel(partnerId);

        List<PmsProductPriceRegulate> regulates = new ArrayList<>();

        for (PmsProductSkuModel model : productSkuModels) {
            PmsProductPriceRegulate regulate = regulateMap.get(model.getSkuCode());
            if (oConvertUtils.isNotEmpty(regulate)){
                regulate.setProductSn(model.getProductSn());
                regulates.add(regulate);
            }
        }
        return regulates;
    }


}
